package com.qigao.mall.web.controller.app.user;

import com.github.pagehelper.PageInfo;
import com.qigao.mall.api.OrderService;
import com.qigao.mall.commons.dto.*;
import com.qigao.mall.commons.enums.OrderActionEnum;
import com.qigao.mall.commons.enums.OrderStatusEnum;
import com.qigao.mall.commons.enums.Result;
import com.qigao.mall.commons.enums.ResultCode;
import com.qigao.mall.commons.exceptions.BusinessException;
import com.qigao.mall.web.config.QiGaoProperties;
import com.qigao.mall.web.controller.AbstractOrderController;
import com.qigao.mall.web.utils.RequestUtils;
import com.qigao.mall.web.utils.ValidatorUtil;
import com.qigao.mall.web.vo.app.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/app/user/order")
@Api(tags = "App订单相关API",value = "App订单相关API")
public class AppOrderController extends AbstractOrderController {
    private static Logger logger= LoggerFactory.getLogger(AppOrderController.class);
    @Resource
    OrderService orderService;
    @Resource
    private QiGaoProperties qiGaoProperties;

    //1.创建订单
    @PostMapping("/createOrder")
    @ApiOperation(value = "创建订单", notes = "创建订单")
    public Result<String> createOrder(@RequestBody OrderCreateVo orderCreateVo, HttpServletRequest request){
        try{
            //参数校验
            ValidatorUtil.validateEntity(orderCreateVo,OrderCreateVo.class);
            OrderCreateDto orderCreateDto=new OrderCreateDto();
            BeanUtils.copyProperties(orderCreateVo,orderCreateDto);
            List<OrderCreateDetailVo> orderCreateDetailVos=orderCreateVo.getOrderCreateDetailVos();
            if(orderCreateDetailVos==null || orderCreateDetailVos.size()==0){
                return Result.newError(ResultCode.COMMON_PARAM_INVALID);
            }
            List orderCreateDtos=new ArrayList();
            for(OrderCreateDetailVo orderCreateDetailVo : orderCreateDetailVos){
                ValidatorUtil.validateEntity(orderCreateDetailVo,OrderCreateDetailVo.class);
                OrderCreateDetailDto orderCreateDetailDto=new OrderCreateDetailDto();
                BeanUtils.copyProperties(orderCreateDetailVo,orderCreateDetailDto);
                orderCreateDetailDto.setCoupAmt(new BigDecimal(orderCreateDetailVo.getCoupAmt()));
                orderCreateDetailDto.setScoreAmt(new BigDecimal(orderCreateDetailVo.getScoreAmt()));
                orderCreateDtos.add(orderCreateDetailDto);
            }
            orderCreateDto.setPayType(orderCreateVo.getPayType().getCode());
            orderCreateDto.setOrderCreateDetailDtoList(orderCreateDtos);
            orderCreateDto.setBuylerId(RequestUtils.getCurrentUserNo(request));
            orderCreateDto.setBuylerName(RequestUtils.getCurrentUserName(request));
            orderCreateDto.setSysName(qiGaoProperties.getSysName());
            return orderService.createOrder(orderCreateDto);
        }catch (BusinessException be){
            logger.error("[创建订单]发生业务异常:{}",be);
            return Result.newError(ResultCode.FAIL.getCode(),be.getMsg());
        }catch (Exception e){
            logger.error("[创建订单]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //2.订单查询列表
    @PostMapping("/findAllOrder")
    @ApiOperation(value = "获取当前用户所在店铺的所有订单列表", notes = "获取当前用户所在店铺（shopNo可传）的所有订单列表")
    public Result<PageInfo<OrderResultDto>> findAllOrder(HttpServletRequest request){
        try{
            //参数校验
            String shopNo=request.getParameter("shopNo");
            OrderQueryDto orderQueryDto=new OrderQueryDto();
            if(!StringUtils.isEmpty(shopNo)){
                orderQueryDto.setShopNo(shopNo);
            }
            orderQueryDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            return  orderService.findOrderByCond(orderQueryDto);
        }catch (Exception e){
            logger.error("[订单查询列表]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //2.按照订单状态查询订单列表
    @PostMapping("/findOrderByStatus")
    @ApiOperation(value = "按照订单状态查询当前用户的订单列表", notes = "按照订单状态查询当前用户的订单列表")
    public Result<PageInfo<OrderResultDto>> findOrderByStatus(@RequestBody OrderQueryVo orderQueryVo, HttpServletRequest request){
        try{
            //参数校验
            OrderQueryDto orderQueryDto=new OrderQueryDto();
            BeanUtils.copyProperties(orderQueryVo,orderQueryDto);
            orderQueryDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            String shopNo=request.getParameter("shopNo");
            if(!StringUtils.isEmpty(shopNo)){
                orderQueryDto.setShopNo(shopNo);
            }
            if(!StringUtils.isEmpty(orderQueryVo.getOrderStatus()))
            orderQueryDto.setOrderStatus(Integer.valueOf(orderQueryVo.getOrderStatus()));
            return  orderService.findOrderByCond(orderQueryDto);
        }catch (Exception e){
            logger.error("[订单查询列表]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }


    //2.按照订单状态查询订单列表
    @PostMapping("/findOrderByRecvUserNo")
    @ApiOperation(value = "按照订单状态查询收货用户的订单列表", notes = "按照订单状态查询收货用户的订单列表")
    public Result<PageInfo<OrderResultDto>> findOrderByRecvUserNo(@RequestBody OrderQueryVo orderQueryVo, HttpServletRequest request){
        try{
            //参数校验
            OrderQueryDto orderQueryDto=new OrderQueryDto();
            orderQueryDto.setUserNo(null);
            orderQueryDto.setRecvUserNo(orderQueryVo.getRecvUserNo());
            String shopNo=request.getParameter("shopNo");
            if(!StringUtils.isEmpty(shopNo)){
                orderQueryDto.setShopNo(shopNo);
            }
            if(!StringUtils.isEmpty(orderQueryVo.getOrderStatus()))
                orderQueryDto.setOrderStatus(Integer.valueOf(orderQueryVo.getOrderStatus()));
            return  orderService.findOrderByRecvUserNo(orderQueryDto);
        }catch (Exception e){
            logger.error("[订单查询列表]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }


    @PostMapping("/findOrderByInviteUserNo")
    @ApiOperation(value = "按照客户查询推荐订单列表", notes = "按照客户查询推荐订单列表")
    public Result<PageInfo<OrderResultDto>> findOrderByInviteUserNo(@RequestBody OrderQueryVo orderQueryVo, HttpServletRequest request){
        try{
            //参数校验
            OrderQueryDto orderQueryDto=new OrderQueryDto();
            orderQueryDto.setUserNo(null);
            orderQueryDto.setRecvUserNo(orderQueryVo.getRecvUserNo());
            String shopNo=request.getParameter("shopNo");
            if(!StringUtils.isEmpty(shopNo)){
                orderQueryDto.setShopNo(shopNo);
            }
            if(!StringUtils.isEmpty(orderQueryVo.getOrderStatus()))
                orderQueryDto.setOrderStatus(Integer.valueOf(orderQueryVo.getOrderStatus()));
            return  orderService.findOrderByInviteUserNo(orderQueryDto);
        }catch (Exception e){
            logger.error("[订单查询列表]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }


    //3.按照订单号查询订单信息
    @PostMapping("/findOrderByNo/{orderNo}")
    @ApiOperation(value = "按照订单号查询订单信息", notes = "按照订单号查询订单信息")
    public Result<OrderResultDto> findOrderByNo(@PathVariable("orderNo")String orderNo){
        try{
            //参数校验
            return orderService.findOrderByNo(orderNo);
        }catch (Exception e){
            logger.error("[订单查询列表]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    //3.按照订单号短码查询某个用户下的订单信息
    @PostMapping("/findOrderByRecv/{orderRecv}")
    @ApiOperation(value = "按照订单号短码查询某个用户下的订单信息", notes = "按照订单号短码查询某个用户下的订单信息")
    public Result<OrderResultDto> findOrderByRecv(@PathVariable("orderRecv")String orderRecv,HttpServletRequest request){
        try{
            //参数校验
            String userNo=RequestUtils.getCurrentUserNo(request);
            return orderService.findOrderByRecv(orderRecv,userNo);
        }catch (Exception e){
            logger.error("[按照订单号短码查询某个用户下的订单信息]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    // 修改订单（地址和备注） |小程序C端|---
    @PostMapping("/updateOrder")
    @ApiOperation(value = "修改订单（地址和备注）", notes = "修改订单（地址和备注）")
    public Result<String> updateMerOrder(@RequestBody UserOrderModiVo userOrderModiVo, HttpServletRequest request){
        //参数校验
        ValidatorUtil.validateEntity(userOrderModiVo,UserOrderModiVo.class);
        try{
            OrderModiDto orderModiDto=new OrderModiDto();
            BeanUtils.copyProperties(userOrderModiVo,orderModiDto);
            orderModiDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            return orderService.updateOrder(orderModiDto);
        }catch (Exception e){
            logger.error("[创建订单]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    @PostMapping("/confirmRecv")
    @ApiOperation(value = "确认收货", notes = "确认收货")
    public Result<String> confirmRecv(@RequestBody OrderConfirmSendVo orderConfirmSendVo, HttpServletRequest request){
        //参数校验
        ValidatorUtil.validateEntity(orderConfirmSendVo,OrderConfirmSendVo.class);
        try{
            OrderModiDto orderModiDto=new OrderModiDto();
            orderModiDto.setOrderAction(OrderActionEnum.CONFIRM_RECV);
            orderModiDto.setOrderNo(orderConfirmSendVo.getOrderNo());
            orderModiDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            orderModiDto.setOrderStatus(OrderStatusEnum.HAS_RECV.getCode());
            return orderService.updateOrderStatus(orderModiDto);
        }catch (Exception e){
            logger.error("[确认发货]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

    @PostMapping("/cancelOrder")
    @ApiOperation(value = "取消订单", notes = "取消订单")
    public Result<String> cancelOrder(@RequestBody OrderConfirmSendVo orderConfirmSendVo, HttpServletRequest request){
        //参数校验
        ValidatorUtil.validateEntity(orderConfirmSendVo,OrderConfirmSendVo.class);
        try{
            OrderModiDto orderModiDto=new OrderModiDto();
            orderModiDto.setOrderAction(OrderActionEnum.ORDER_CANCEL);
            orderModiDto.setOrderNo(orderConfirmSendVo.getOrderNo());
            orderModiDto.setUserNo(RequestUtils.getCurrentUserNo(request));
            orderModiDto.setOrderStatus(OrderStatusEnum.CLOSE.getCode());
            return orderService.updateOrderStatus(orderModiDto);
        }catch (Exception e){
            logger.error("[确认发货]发生异常:{}",e);
            return Result.newError(ResultCode.FAIL);
        }
    }

}
